package com.pdd.mall.controller;

import com.pdd.mall.common.api.CommonResult;
import com.pdd.mall.dto.AddressParam;
import com.pdd.mall.entity.Address;
import com.pdd.mall.entity.User;
import com.pdd.mall.service.AddressService;
import com.pdd.mall.service.UserService;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 地址控制器
 */
@RestController
@RequestMapping("/user/addresses")
public class AddressController {
    
    @Autowired
    private AddressService addressService;
    
    @Autowired
    private UserService userService;
    
    @GetMapping
    public CommonResult<List<Address>> getAddressList() {
        Long userId = getCurrentUserId();
        List<Address> addressList = addressService.getAddressList(userId);
        return CommonResult.success(addressList);
    }
    
    @GetMapping("/{id}")
    public CommonResult<Address> getAddress(@PathVariable Long id) {
        Long userId = getCurrentUserId();
        Address address = addressService.getAddress(id, userId);
        if (address == null) {
            return CommonResult.notFound("地址不存在");
        }
        return CommonResult.success(address);
    }
    
    @PostMapping
    public CommonResult<Address> addAddress(@RequestBody @Valid AddressParam param) {
        Long userId = getCurrentUserId();
        Address address = addressService.addAddress(param, userId);
        return CommonResult.success(address);
    }
    
    @PutMapping("/{id}")
    public CommonResult<Address> updateAddress(@PathVariable Long id, @RequestBody @Valid AddressParam param) {
        Long userId = getCurrentUserId();
        Address address = addressService.updateAddress(id, param, userId);
        if (address == null) {
            return CommonResult.notFound("地址不存在");
        }
        return CommonResult.success(address);
    }
    
    @DeleteMapping("/{id}")
    public CommonResult<String> deleteAddress(@PathVariable Long id) {
        Long userId = getCurrentUserId();
        boolean success = addressService.deleteAddress(id, userId);
        if (success) {
            return CommonResult.success(null);
        } else {
            return CommonResult.notFound("地址不存在");
        }
    }
    
    /**
     * 获取当前登录用户ID
     */
    private Long getCurrentUserId() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        User user = userService.getUserByUsername(username);
        return user.getId();
    }
}
